package com.partyjoin.project.module.conference.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.partyjoin.common.constant.Constants;
import com.partyjoin.common.utils.DateUtils;
import com.partyjoin.common.utils.security.ShiroUtils;
import com.partyjoin.framework.aspectj.lang.annotation.Log;
import com.partyjoin.framework.aspectj.lang.constant.BusinessType;
import com.partyjoin.framework.web.controller.BaseController;
import com.partyjoin.framework.web.domain.AjaxResult;
import com.partyjoin.framework.web.page.TableDataInfo;
import com.partyjoin.project.module.conference.domain.Conference;
import com.partyjoin.project.module.conference.service.IConferenceService;
import com.partyjoin.project.module.prepareEvolve.domain.PrepareEvolve;
import com.partyjoin.project.module.prepareEvolve.service.IPrepareEvolveService;
import com.partyjoin.project.module.proposer.domain.Proposer;
import com.partyjoin.project.module.proposer.service.IProposerService;
import com.partyjoin.project.system.dept.service.IDeptService;
import com.partyjoin.project.system.user.domain.User;
import com.partyjoin.project.system.user.service.IUserService;

/**
 * 会议记录 信息操作处理
 * 
 * @author 莫东林
 * @date 2018-07-19
 */
@Controller
@RequestMapping("/module/conference")
public class ConferenceController extends BaseController
{
    private String prefix = "module/conference";
	
	@Autowired
	private IConferenceService conferenceService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IPrepareEvolveService prepareEvolveService;
	
	@Autowired
	private IProposerService proposerService;
	
	@Autowired
	private IDeptService deptService;
	
	
	/**
	 * 添加党委审核预备党员会议
	 */
	@RequiresPermissions("module:conference:add")
	@GetMapping("/addPrepare")
	public String addPrepare(){
		return prefix + "/addPrepare";
	}
	
	/**
	 * 打开会议列表
	 * @param conference
	 * @param model
	 * @return
	 */
	@RequiresPermissions("module:conference:view")
	@GetMapping()
	public String conference(Conference conference, Model model)
	{
	    return prefix + "/conferences";
	}
	
	/**
	 * 备案获取会议下拉信息(未进行备案的)
	 */
	@RequiresPermissions("module:conference:list")
	@GetMapping("/getConferenceList")
	@ResponseBody
	public Object getConferenceList(Conference conference){
		conference.setDeptId(ShiroUtils.getUserDeptId());
		List<Conference> cList = conferenceService.selectConferenceListNotRecord(conference);
		Map<String, Object> list = new HashMap<String, Object>();
		List<Object> array = new ArrayList<Object>();
		list.put("message", "");
		list.put("code", 200);
		list.put("redirect", "");
		for(Conference c : cList){
			Map<String, Object> info = new HashMap<String, Object>();
			info.put("conferenceId", c.getConferenceId());
			info.put("conferenceName", c.getConferenceName());
			info.put("时间", c.getConferenceTime());
			info.put("备注", "呵呵呵呵");
			array.add(info);
		}
		list.put("value", array);
		return list;
	}
	
	/**
	 * 查询会议记录列表
	 */
	@RequiresPermissions("module:conference:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Conference conference, Model model)
	{
		if(conference.getDeptId() == null){
			conference.setDeptId(ShiroUtils.getUserDeptId());
		}
		List<Conference> list = conferenceService.selectConferenceList(conference);
		for(int i = 0; i < list.size(); i++){
			list.get(i).setDeptName(deptService.selectNameById(list.get(i).getDeptId()));
		}
		//根据会议Id名单查找姓名名单
//		for(Conference c: list){
//			String successList = c.getSuccessList();
//			String failList = c.getFailList();		
//			String successName = "";//存放决议通过姓名名单
//			String failName = "";//存放决议未通过姓名名单
//			
//			//构造未通过姓名名单
//			if(failList == null){
//				c.setFailListName(null);
//			}else{
//				String[] fList = failList.split(",");
//				for(String id : fList){
//					User user = userService.selectUserById(Long.valueOf(id));
//					failName += user.getUserName() + ",";
//				}
//				c.setFailListName(failName.substring(0, failName.length() - 2));
//			}
//			
//			//构造通过姓名名单
//			if(successList == null){
//				c.setSuccessListName(null);
//			}else{
//				String[] sList = successList.split(",");
//				for(String id : sList){
//					User user = userService.selectUserById(Long.valueOf(id));
//					successName += user.getUserName() + ",";
//				}
//				c.setSuccessListName(successName.substring(0, successName.length() - 2));
//			}
//			
//		}
        return getDataTable(list);
	}
	
	/**
	 * 新增会议记录
	 */
	@RequiresPermissions("module:conference:add")
	@Log(title = "会议记录", action = BusinessType.INSERT)
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}

	/**
	 * 修改会议记录
	 */
	@RequiresPermissions("module:conference:edit")
	@Log(title = "会议记录", action = BusinessType.UPDATE)
	@GetMapping("/edit/{conferenceId}")
	public String edit(@PathVariable("conferenceId") Integer conferenceId, Model model)
	{
		Conference conference = conferenceService.selectConferenceById(conferenceId);
		model.addAttribute("conference", conference);
	    return prefix + "/edit";
	}
	
	/**
	 * 根据Id查询
	 */
	@RequiresPermissions("module:conference:view")
	@GetMapping("/selectConferenceById")
	@ResponseBody
	public Conference selectConferenceById(@RequestParam(value = "id") Integer id, @RequestParam(value = "type") String type){
		Conference conference = conferenceService.selectConferenceById(id);
		//tt为积极分子备案时的码（需要格式化决议名单）
		if(type.equals("tt")){
			
			String successList = conference.getSuccessList();
			String[] successLists = successList.split(",");//分割
			String successNames = "";//存储决议通过者的真实姓名
			for(String userId : successLists){
				User user = userService.selectUserById(Long.parseLong(userId));
				successNames += user.getUserName() + "  ";
			}
			//存放通过名单
			conference.setRemark(successNames);
		}
		return conference;
	}
	
	/**
	 * 保存党委预备党员会议
	 */
	@RequiresPermissions("module:conference:save")
	@Log(title = "会议记录", action = BusinessType.SAVE)
	@PostMapping("/savePrepare")
	@ResponseBody
	public AjaxResult savePrepare(@RequestParam(value = "sList[]") String[] sList, @RequestParam(value = "fList[]") String[] fList,
			@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "date") String date,
			@RequestParam(value = "contents") String contents,
			Conference conference, @RequestParam(value = "prepareEvolveId[]") String[] prepareEvolveId){
		PrepareEvolve prepareEvolve = prepareEvolveService.selectPrepareEvolveById(Integer.valueOf(prepareEvolveId[0]));
		System.out.println(prepareEvolve.getPrepareEvolveId());
//		conference.setConferenceType(Integer.valueOf(id));

		//保存会议内容(待完善)
		if(!contents.equals(",<p><br></p>")){
			
		}
		User user = ShiroUtils.getUser();
		//解析决议通过名单
		String successIds = "";
		String failIds = "";
		for(String id : sList){
			successIds += id + ",";
		}
		//解析决议未通过名单
		for(String id : fList){
			failIds += id + ",";
			if(id.equals("999")){
				failIds = null;
				break;
			}
		}
		if(upload(conference, file, Constants.CONFERENCE_VOTE)){
			conference.setConferenceVote("/" + DateUtils.getDate() + "/" + conference.getConferenceName()+ "/" + file.getOriginalFilename());
		}
		prepareEvolve.setUpdateBy(ShiroUtils.getLoginName());
		prepareEvolve.setUpdateTime(DateUtils.getNowDate());
		prepareEvolve.setDisposeTime(DateUtils.getNowDate());
		prepareEvolve.setSuccessList(successIds);
		prepareEvolve.setFailList(failIds);
		prepareEvolve.setState(1);
		//更新发展对象变更为预备党员
				String[] userIds = prepareEvolve.getSuccessList().split(",");
				Long[] roleIds = {Constants.PREPARE_ROLE_ID};
				if(userIds != null && userIds.length > 0 && !userIds.equals("")){
					for(String userId : userIds){
						User users = userService.selectUserById(Long.parseLong(userId));
						Proposer update = proposerService.selectProposerById(users.getUserId());
						Conference c = conferenceService.selectConferenceById(prepareEvolve.getConferenceIdSecond());
						update.setPrepareTime(c.getConferenceTime());
						proposerService.updateProposer(update);
						//销毁发展对象角色
						userService.removeUserRole(Long.parseLong(userId), Constants.DEVELOPMENT_ROLE_ID);
						users.setRoleIds(roleIds);
						userService.insertUserRole(users);
					}
				}
		prepareEvolve.setUpdateBy(ShiroUtils.getLoginName());
		prepareEvolve.setUpdateTime(DateUtils.getNowDate());
		prepareEvolve.setDisposeTime(DateUtils.getNowDate());
		prepareEvolve.setSuccessList(successIds);
		prepareEvolve.setFailList(failIds);
		prepareEvolve.setState(1);
		
		conference.setDeptId(ShiroUtils.getUserDeptId());
		conference.setState(0);
		conference.setFailList(failIds);
		conference.setSuccessList(successIds);
		conference.setProposerList(successIds + failIds); 
		conference.setConferenceTime(DateUtils.dateTime("yyyy-MM-dd", date));
		conference.setCreateBy(user.getUserName());
		conference.setCreateTime(DateUtils.getNowDate());
		if (conferenceService.saveConference(conference) > 0)
		{
			if(prepareEvolveService.updatePrepareEvolve(prepareEvolve) > 0){
				return success();
			}
		}
		return error();
	}
	
	/**
	 * 保存会议记录
	 */
	@RequiresPermissions("module:conference:save")
	@Log(title = "会议记录", action = BusinessType.SAVE)
	@PostMapping("/save")
	@ResponseBody
	public AjaxResult save(@RequestParam(value = "sList[]") String[] sList, @RequestParam(value = "fList[]") String[] fList,
			@RequestParam(value = "type[]") String[] tList,
			@RequestParam(value = "file") MultipartFile file, 
			@Param(value = "vote")MultipartFile vote,
			@RequestParam(value = "date") String date,
			@RequestParam(value = "contents") String contents,
			Conference conference)
	{
		for(String id : tList){
			conference.setConferenceType(Integer.valueOf(id));
		}
		
		//保存会议内容(待完善)
		if(!contents.equals(",<p><br></p>")){
			
		}
		User user = ShiroUtils.getUser();
		//解析决议通过名单
		String successIds = "";
		String failIds = "";
		for(String id : sList){
			successIds += id + ",";
		}
		//解析决议未通过名单
		for(String id : fList){
			failIds += id + ",";
			if(id.equals("999")){
				failIds = null;
				break;
			}
		}
		//如果投票文件为空
		if(vote.getSize() != 0){
			upload(conference, vote, Constants.CONFERENCE_VOTE);
			conference.setConferenceVote("/" + DateUtils.getDate() + "/" + conference.getConferenceName()+ "/" + vote.getOriginalFilename());
		}
		if(upload(conference, file, Constants.CONFERENCE_EVENTSUMMARY)){
			conference.setConferenceEventsummary("/" + DateUtils.getDate() + "/" + conference.getConferenceName()+ "/" + file.getOriginalFilename());
		}
		conference.setDeptId(ShiroUtils.getUserDeptId());
		conference.setState(0);
		conference.setFailList(failIds);
		conference.setSuccessList(successIds);
		conference.setProposerList(successIds + failIds); 
		conference.setConferenceTime(DateUtils.dateTime("yyyy-MM-dd", date));
		conference.setCreateBy(user.getUserName());
		conference.setCreateTime(DateUtils.getNowDate());
		if (conferenceService.saveConference(conference) > 0)
		{
			return success();
		}
		return error();
	}
	
	/**
	 * 文件上传
	 */
	public boolean upload(Conference conference, MultipartFile file, String type){
		boolean success = false;
		try {
			File document = null;
			String fileName = file.getOriginalFilename();  
			File firstFolder = new File(type);
			File secondFolder = new File(firstFolder + "/" + DateUtils.getDate() + "/" + conference.getConferenceName());
			if(!firstFolder.exists()){
				firstFolder.mkdirs();
			}
			if(!secondFolder.exists()){
				secondFolder.mkdirs();
			}
			document = new File(secondFolder+"/",fileName);
			System.out.println("文件上传路径"+ document);
	        file.transferTo(document); 
	        success = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return success;
	}
	
	/**
	 * 删除会议记录
	 */
	@RequiresPermissions("module:conference:remove")
	@Log(title = "会议记录", action = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		int rows = conferenceService.deleteConferenceByIds(ids);
		if (rows > 0)
        {
            return success();
        }
        return error();
	}
	
}
